package web.action.com;


import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.joint.base.entity.Company;
import com.joint.base.entity.Permission;
import com.joint.base.service.PermissionService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;
import web.action.BaseAdminAction;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hpj on 2014/9/16.
 */
@ParentPackage("com")
public class AjaxPermissionAction extends BaseAdminAction {
    @Resource
    private PermissionService permissionService;

    private Permission permission;

    private String name;
    private String businessKey;
    private String url;
    private String parentId;
    private String type;
    private String iconCls;
    private String iconcolor;
    private int sortNumber;
    private List<Map<String, Object>> permissionArrayList;


    public String save() {
        if (StringUtils.isNotEmpty(keyId)) {
            permission = permissionService.get(keyId);
        } else {
            permission = new Permission();
        }
        permission.setName(name);
        permission.setState(BaseEnum.StateEnum.Enable);
        permission.setUrl(url);
        permission.setSortNumber(sortNumber);
        permission.setBusinessKey(businessKey);
        permission.setType(type);
        permission.setIconCls(iconCls);
        permission.setIconcolor(iconcolor);
        permission.setCreater(usersService.getLoginInfo());
        permission.setCompany(usersService.getCompanyByUser());
        if (StringUtils.isEmpty(parentId)) {
            permission.setLevel(1);
        } else {
            String[] array = parentId.split(",");
            for (String item : array) {
                if (StringUtils.isNotEmpty(item)) {
                    Permission parentPer = permissionService.get(item);
                    int parentLevel = parentPer.getLevel();
                    permission.setLevel(parentLevel + 1);
                    permission.setParent(permissionService.get(item));
                }
            }
        }
        if (StringUtils.isNotEmpty(keyId)) {
            permissionService.update(permission);
        } else {
            permissionService.save(permission);
        }
        return ajaxHtmlCallback("200", "提交成功!", "操作状态");
    }

    public String zTree() {
        Company company = usersService.getCompanyByUser();
        Pager pager = new Pager(0);
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("sortNumber");
        pager.setOrderType(BaseEnum.OrderType.asc);
        List<Permission> permissionList = (List<Permission>) permissionService.findByPagerAndCompany(pager, null, company, new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable}).getList();
        List<JSONObject> treeList = new ArrayList<JSONObject>();
        for (Permission per : permissionList) {
            Map<String, Object> rMap = new HashMap<String, Object>();
            rMap.put("id", per.getId());
            rMap.put("pId", per.getParent() == null ? "" : per.getParent().getId());
            rMap.put("pName", per.getName());
            rMap.put("name", per.getLevel() + "|" + per.getName());
            rMap.put("sName", per.getName());
            rMap.put("intLevel", per.getLevel());
            rMap.put("open", false);

            treeList.add(JSONObject.fromObject(rMap));
        }
        Map<String, Object> data = new HashMap<String, Object>();
        data = new HashMap<String, Object>();
        data.put("data", JSONArray.fromObject(treeList));

        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
    }

    public String jqGrid() {
        List<JSONObject> dataRows = new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        if (StringUtils.isNotEmpty(keyId)) {
            Permission per = permissionService.get(keyId);
            dataRows = getPerMap(per, dataRows);
        }
        //分页
        int records = dataRows.size();
        int total = records;
        if (total % rows == 0) {
            total = total / rows;
        } else {
            if (total < rows) {
                total = 1;
            } else {
                total = total / rows + 1;
            }
        }
        int firstRow = (page - 1) * rows;
        int endRow = page * rows;
        if (endRow > records) {
            endRow = records;
        }
        List<JSONObject> dataRowsPage = new ArrayList<JSONObject>();
        for (int i = firstRow; i < endRow; i++) {
            dataRowsPage.add(dataRows.get(i));
        }

        data.put("dataRows", JSONArray.fromObject(dataRowsPage));
        data.put("records", records);
        data.put("page", page);
        data.put("rows", rows);
        data.put("total", total);
        return ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String input() {
        if (StringUtils.isNotEmpty(keyId)) {
            permission = permissionService.get(keyId);
        }
        List<Permission> permissionList = permissionService.getAll();
        Map<String, Object> map;
        permissionArrayList = new ArrayList<Map<String, Object>>();
        for (Permission per : permissionList) {
            map = new HashMap<String, Object>();
            map.put("id", per.getId());
            map.put("name", per.getName());
            map.put("checked", "");
            permissionArrayList.add(map);
        }
        return "input";
    }

    /**
     * 获取第一级导航的json数据
     *
     * @return
     */
    public String navList() {
        List<Permission> perList = permissionService.findAllByType("navigation");
        List<JSONObject> dataRows = Lists.newArrayList();
        Map<String, Object> data = Maps.newHashMap();
        Map<String, Object> rMap = null;
        for (Permission per : perList) {
            rMap = Maps.newHashMap();
            rMap.put("name", per.getName());
            rMap.put("url", per.getUrl());
            rMap.put("id", per.getId());
            rMap.put("key", per.getBusinessKey());
            rMap.put("icon", per.getIconCls());
            rMap.put("color", per.getIconcolor());
            dataRows.add(JSONObject.fromObject(rMap));
        }
        data.put("dataRows", JSONArray.fromObject(dataRows));
        data.put("state", "200");
        return ajaxJson(JSONObject.fromObject(data).toString());
    }

    /**
     * 获取左侧导航的json数据
     *
     * @return
     */
    public String leftList() {
        Permission per = permissionService.get(keyId);
        Map<String, Object> data = Maps.newHashMap();
        List<JSONObject> dataRows = Lists.newArrayList();
        List<Permission> permissionList = permissionService.getAllByUser(usersService.getLoginInfo().getId());
        for (Permission permission : per.getChildren()) {
            if (permissionList.contains(permission)) {
                dataRows.add(getListInfo(permission));
            }
        }
        data.put("dataRows", JSONArray.fromObject(dataRows));
        data.put("state", "200");
        return ajaxJson(JSONObject.fromObject(data).toString());
    }

    private JSONObject getListInfo(Permission per) {
        Map<String, Object> rMap = Maps.newHashMap();
        List<JSONObject> dataRows = Lists.newArrayList();
        rMap.put("name", per.getName());
        rMap.put("url", per.getUrl());
        rMap.put("id", per.getId());
        rMap.put("key", per.getBusinessKey());
        rMap.put("icon", per.getIconCls());
        if (per.getChildren() != null && per.getChildren().size() > 0) {
            for (Permission permission : per.getChildren()) {
                dataRows.add(getListInfo(permission));
            }
            rMap.put("child", JSONArray.fromObject(dataRows).toString());
        }
        return JSONObject.fromObject(rMap);
    }


    private List<JSONObject> getPerMap(Permission per, List<JSONObject> dataRows) {
        Map<String, Object> rMap = new HashMap<String, Object>();
        rMap.put("id", per.getId());
        rMap.put("name", per.getName());
        rMap.put("pName", "");
        if (per.getParent() != null) {
            rMap.put("pName", per.getParent().getName());
        }
        rMap.put("businessKey", per.getBusinessKey());
        rMap.put("iconCls", per.getIconCls());
        rMap.put("type", per.getType());
        rMap.put("level", per.getLevel());
        rMap.put("url", per.getUrl());
        rMap.put("sortNumber", per.getSortNumber());
        if (per.getChildren() != null) {
            for (Permission childPer : per.getChildren()) {
                if (childPer.getState().equals(BaseEnum.StateEnum.Enable)) {
                    getPerMap(childPer, dataRows);
                }
            }
        }
        dataRows.add(JSONObject.fromObject(rMap));
        return dataRows;
    }


    public String delete() throws Exception {
        if (StringUtils.isEmpty("keyId")) {
            return ajaxHtmlCallback("200", "请选择资源！", "操作状态");
        }
        permission = permissionService.get(keyId);
        permission.setState(BaseEnum.StateEnum.Delete);
        permissionService.update(permission);
        return ajaxHtmlCallback("200", "删除成功！", "操作状态");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public int getSortNumber() {
        return sortNumber;
    }

    public void setSortNumber(int sortNumber) {
        this.sortNumber = sortNumber;
    }

    public Permission getPermission() {
        return permission;
    }

    public void setPermission(Permission permission) {
        this.permission = permission;
    }

    public String getParentId() {
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId;
    }

    public String getBusinessKey() {
        return businessKey;
    }

    public void setBusinessKey(String businessKey) {
        this.businessKey = businessKey;
    }

    public List<Map<String, Object>> getPermissionArrayList() {
        return permissionArrayList;
    }

    public void setPermissionArrayList(List<Map<String, Object>> permissionArrayList) {
        this.permissionArrayList = permissionArrayList;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getIconCls() {
        return iconCls;
    }

    public void setIconCls(String iconCls) {
        this.iconCls = iconCls;
    }

    public String getIconcolor() {
        return iconcolor;
    }

    public void setIconcolor(String iconcolor) {
        this.iconcolor = iconcolor;
    }
}
